package com.xxxx.seckill.config;

import com.alibaba.fastjson.JSON;
import com.xxxx.seckill.pojo.User;
import com.xxxx.seckill.utils.CookieUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@Component
public class UserArgumentResolver implements HandlerMethodArgumentResolver {

    public static final ThreadLocal<User> userLocal = new ThreadLocal<User>();
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        //判断拦截的参数是否为 User
        Class<?> aClass = parameter.getParameterType();
        return aClass.equals(User.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        log.error("参数适配器工作中。。。。。。");
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        String cookie = CookieUtil.getCookieValue(request, "user");
        if (StringUtils.isEmpty(cookie)){
            return null;
        }
        String obj = (String) redisTemplate.opsForValue().get("user:" + cookie);
        if (StringUtils.isEmpty(obj)){
            return null;
        }
        User user = JSON.parseObject(obj, User.class);
        userLocal.set(user);
        return user;
    }
}
